import { useWebSocket } from "@/utils/WebSocket.js";
const socketStore = defineStore("socket", {
  state: () => ({
    // 销售额统计
    festival_order_stat: {
      income: 0, // 销售额
      count: 0, //订单量
      avg_order_price: 0, // 客单价
    },
    // 销售额 排行版
    festival_sales_ranking: {
      platform_ranking: [],
      total_ranking: {
        category_ranking: [],
        department_ranking: {
          first_depart_ranking: [],
          second_depart_ranking: [],
        },
      },
    },
    // 销售额 按站点统计
    festival_site_country_stat: [],
    // 弹幕
    bullet_screen: {},
    //未读消息
    un_view_message_total:{
      unView:0
    },
    //消息通知
    card_notice_message:{

    },
    wsInstance: null,
  }),
  actions: {
    setSocketStore(params) {
      let par = JSON.parse(params)
      this[par.event] = par.payload
    },
    openWebSocket(url) {
      if (this.wsInstance) return; // 防止重复创建
      this.wsInstance = useWebSocket(url, {
        heartbeatInterval: 10000,
      });
      this.wsInstance.on('open', () => console.log('WebSocket connected'));
      this.wsInstance.on('message', (msg) => {
        console.log('Received message:', msg);
        this.setSocketStore(msg);
        // 在此处理接收到的消息，可能需要更新其他 store 或执行其他操作
      });
      this.wsInstance.on('error', (error) => console.error('WebSocket error:', error));
      this.wsInstance.on('close', () => console.log('WebSocket disconnected'));
    },
    closeWebSocket(val) {
      if (!this.wsInstance) return; // 防止重复关闭
      this.wsInstance.cleanup(val)
      this.wsInstance = null
    },
    sendMessage(message) {
      if (this.wsInstance) {
        this.wsInstance.send(JSON.stringify(message));
      } else {
        console.error('WebSocket is not connected');
      }
    },
  },
})

export default socketStore
